<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Hash;
use Log;
//20210319
class MiniController extends Controller
{
    public function MiniLogin(Request $request){
        $info = $request->all();
        $mini = \EasyWeChat::miniProgram();
        $result = $mini->auth->session($info['code']);
        $users = Db::table('admin_users')->where(['username'=>$info['username']])->first();
        if (Hash::check($info['password'],$users->password)) {
            Db::table('admin_users')->where(['username'=>$info['username']])->update(['openid'=>$result['openid']]);
            $user = Db::table('admin_users')->where(['id'=>$users->id,'openid'=>$result['openid']])->first();
            $role = Db::table('admin_role_users')->where(['user_id'=>$users->id])->first();
            $body['adminId'] = $users->id;
            $body['openid'] = $result['openid'];
            $user->role = $role->role_id;
            $body['user'] = $user;
            $arr = ['resultCode'=>1,'resultMsg'=>'登陆成功','resultBody'=>$body];
        }else{
            $arr = ['resultCode'=>0,'resultMsg'=>'账号或密码错误！'];//密码错误
        }
        return $arr;
    }
    //登出 删除openid unionid
    public function MiniLogout(Request $request){
        $info = $request->all();
        $users = Db::table('admin_users')->where(['username'=>$info['username']])->first();
        if (isset($users)) {
            Db::table('admin_users')->where(['username'=>$info['username']])->update(['openid'=>'','unionid'=>'']);
            $arr = ['state'=>1,'msg'=>'登出成功！'];
            //密码正确getDevicelist
        }else{
            $arr = ['state'=>0,'msg'=>'无此账号！'];//密码错误
        }
        return $arr;
    }

    public function uploadimg(Request $request){
        $Path = "upload/images/detail/";
        if (!empty($_FILES['file'])) {
            //获取扩展名
            $exename = $this->getExeName($_FILES['file']['name']);

            if ($exename != 'png' && $exename != 'jpg' && $exename != 'gif') {
                exit('不允许的扩展名');
            }
            // $fileName = $_SERVER['DOCUMENT_ROOT'] . $Path . date('Ym');//文件路径
            $upload_name = 'upload/images/detail/img_' . date("YmdHis") . rand(0, 100) . '.' . $exename;//文件名加后缀
            if (!file_exists($Path)) {
                //进行文件创建
                mkdir($Path, 0777, true);
            }
            // $imageSavePath = $upload_name;
            if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_name)) {
                return json_encode($upload_name);
            }
        }

    }

    public function getExeName($fileName){
        $pathinfo = pathinfo($fileName);
        return strtolower($pathinfo['extension']);
    }

    //添加设备
    public function adddevice(Request $request){
        $info = $request->all();
        $device = Db::table('xfy_device')->where(['cid'=>$info['cid']])->first();
        if($device){
            $res['status'] = 0;
            $res['msg'] = '该设备已添加过！';
            return json_encode($res);
        }
        // Cache::forget('authtoken');
        $info['cid'] = $info['device_type']==2?substr($info['cid'],6,15):$info['cid'];

        if($info['device_type']==3){
            $add_res = $this->testadd($info['cid']);
        }else{
            $add_res = $this->deviceAdd($info['cid'],Cache::get('authtoken'),$info['device_type']);
        }
        if(isset($add_res['error_code'])){ //添加失败
            $res['status'] = 0;
            $res['msg'] = $add_res['error_desc'];
        }else{
            $arr = explode(",", $info['picker']);
            $info['province'] = $arr[0];
            $info['city'] = $arr[1];
            $info['area'] = $arr[2];
            unset($info['picker']);
            unset($info['_url']);
            $info['created_at'] = date("Y-m-d H:i:s");
            $info['updated_at'] = date("Y-m-d H:i:s");
            $info['avatar'] = trim($info['avatar'],'"');
            $info['gatewayId'] = $add_res['deviceId'];
            $id = Db::table('xfy_device')->insertGetId($info);
            //区分是否未输入输出
//          if($info['device_type']==3){
//              DB::table('xfy_device')->insert([
//                  ['cid'=>'DI1','devicename'=>'DI1','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'DI2','devicename'=>'DI2','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'DI3','devicename'=>'DI3','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'DI4','devicename'=>'DI4','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'AI1','devicename'=>'AI1','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'AI2','devicename'=>'AI2','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'AI3','devicename'=>'AI3','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//                  ['cid'=>'AI4','devicename'=>'AI4','created_at'=>date("Y-m-d H:i:s"),'projectId'=>$info['projectId'],'pid'=>$id],
//              ]);
//          }
            $res['status'] = 1;
            $res['msg'] = '添加成功';
        }
        return json_encode($res);
    }

    public function deviceAdd($imei,$accessToken,$device_type){// GDHS90BWNB
        if($device_type==4){ //微信锁
            require '../vendor/iot_sdk/Test.php';
            $t = new \Test();
            $productKey = 'a1zQYVHQ92L';
            $deviceName = $imei;
            $result = $t->registDeviceTest($productKey, $deviceName);
            return $res;
        }
        if (!Cache::has('authtoken')) { //鉴权
            $this->authentication();
        }
        if($device_type==1){ //霍尼
            $dtype = 'GDHS90BWNB';
            $manu = 'Hisense';
            $devicetype = 'Smoke';
        }elseif ($device_type==2) { //川大
            $dtype = 'NB20';
            $manu = 'Cdsoft';
            $devicetype = 'Smoke';
        }else{//NB
            $this->testadd($imei);
            $dtype = 'SM001'; //输入输出
            $manu = 'XBWLW';//厂家ID
            $devicetype = 'Switch';
        }
        // $dtype = $device_type==2?'NB20':'GDHS90BWNB';
        // $manu = $device_type==2?'Cdsoft':'Hisense';
        //添加设备
        //测试appId XDkLPjvjfEhkym1rjiz_TH0zvZsa 正式 86y97uYn78Try5i1zFdTLiErnX4a
        //正式 https://device.api.ct10649.com:8743 测试 https://develop.ct10649.com:8093
        // $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
        //app_key 测试 XDkLPjvjfEhkym1rjiz_TH0zvZsa 正式 86y97uYn78Try5i1zFdTLiErnX4a
        //  $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
        // $header = array('Content-Type:application/json','Authorization:Bearer 58a39127ea29403badd0ddc5c0154b02','app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        // $data = '{"verifyCode":"869512030307544","nodeId":"869512030307544","deviceInfo":{"manufacturerId":"Hisense","manufacturerName":"Hisense","deviceType":"Smoke","model":"GDHS90BWNB","protocolType":"CoAP"}}';
        // $result = $this->postSsl($url,$data,$header);


        $dtype = 'GDHS90BWNB';
        $manu = 'Hisense';
        $devicetype = 'Smoke';
        $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';

        $header = array('Content-Type:application/json','Authorization:Bearer '.$accessToken,'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        $data = '{"verifyCode":"'.$imei.'","nodeId":"'.$imei.'","deviceInfo":{"manufacturerId":"'.$manu.'","manufacturerName":"'.$manu.'","deviceType":"'.$devicetype.'","model":"'.$dtype.'","protocolType":"CoAP"}}';
        $a = $this->postSsl($url,$data,$header);

        $res = json_decode($a['return'],1);

        return $res;
    }
    //测试环境
    public function testadd($imei){
        // $add_res = $this->deviceAdd($info['cid'],Cache::get('authtoken'),'868474049209404');
        if (!Cache::has('authtoken1')) { //鉴权
            $this->authentication1();
        }
        $accessToken = Cache::get('authtoken1');
        // print_r($accessToken);die;
        $url = 'https://180.101.147.89:8843/iocm/app/reg/v1.1.0/deviceCredentials?appId=XDkLPjvjfEhkym1rjiz_TH0zvZsa';
        $header = array('Content-Type:application/json','Authorization:Bearer '.$accessToken,'app_key:XDkLPjvjfEhkym1rjiz_TH0zvZsa');
        $data = '{
            "verifyCode":"'.$imei.'",
            "nodeId":"'.$imei.'",
            "deviceInfo":{
                "manufacturerId":"a682ea46551d4f6fadff955c2768a21f",
                "manufacturerName":"XBWLW",
                "deviceType":"Switch",
                "model":"SM001",
                "protocolType":"CoAP"
            }}';
        $a = $this->postSsl($url,$data,$header);
        $res = json_decode($a['return'],1);
        return $res;
    }

    //鉴权
    public function authentication(){
        $data = 'appId=86y97uYn78Try5i1zFdTLiErnX4a&secret=aayy3kB2YJGh1FCpeyxGsyC_uCAa';
        $url = 'https://device.api.ct10649.com:8743/iocm/app/sec/v1.1.0/login';
        $header = ["Content-Type" => "application/x-www-form-urlencoded;"];//貌似不需要,默认就是
        $a = $this->postSsl($url,$data,$header);
        if($a['status']==1){
            $return = json_decode($a['return'],1);
            Cache::add('authtoken', $return['accessToken'], 3000);
        }
    }
    //测试地址鉴权
    public function authentication1(){
        $data = 'appId=XDkLPjvjfEhkym1rjiz_TH0zvZsa&secret=whJRKIeUraiCwzQOIaBUnjN0g7Ya';
        $url = 'https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login';
        $header = ["Content-Type" => "application/x-www-form-urlencoded;"];//貌似不需要,默认就是
        $a = $this->postSsl($url,$data,$header);
        if($a['status']==1){
            $return = json_decode($a['return'],1);
            Cache::add('authtoken1', $return['accessToken'], 3000);
        }
    }

    public function Callback(){
        if (!Cache::has('authtoken')) { //鉴权
            $this->authentication();
        }
        //设置回调
        $url = 'https://device.api.ct10649.com:8743/iocm/app/sub/v1.2.0/subscriptions';
        $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        // $data = '{"notifyType":"deviceAdded","callbackUrl":"http://xbxfy.benpuji.com/api/deviceAdd","channel":"HTTP"}';
        // $data = '{"notifyType":"deviceInfoChanged","callbackUrl":"http://xbxfy.benpuji.com/api/deviceInfo","channel":"HTTP"}';
        $data = '{"notifyType":"deviceDataChanged","callbackUrl":"http://xbxfy.benpuji.com/api/deviceData","channel":"HTTP"}';
        $a = $this->postSsl($url,$data,$header);
        // print_r($a);die;
    }


    function postSsl($url, $data, $header) {
        //if (is_array($data)) {
        //    $data = http_build_query($data);
        //}
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(__FILE__))).'/server.crt');
        curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(__FILE__))).'/server.key');
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        $ret = ['status' => 1];
        if ($error = curl_errno($curl)) {
            $ret['status'] = 0;
            $ret['return'] = $error;
        } else {
            $ret['return'] = $res;
        }
        curl_close($curl); // 关闭CURL会话
        return $ret; // 返回数据
    }

    public function sendOff(){
        $data = '{
             "expireTime": 1800,
             "callbackUrl":  "https://callbackurl",
             "deviceId": "00beae39-09dc-483a-ad57-eeef33d3fd98",
             "command": {
              "identifier": "123",
              "msgType": "cloudReq",
              "serviceId": "Smoke",
              "cmd": "SET_COMMAND",
              "hasMore": 0,
              "mid": 2016,
              "method": "SET_COMMAND",
               "paras": {
               "rawData": "{\"cmdId\":1,\"command\":1,\"periodType\":1,\"period\":60}"
              }
             }
            }';

    }

    public function getCompanyinfo($openid){
        $user = Db::table('admin_users')->where(['openid'=>$openid])->first();
        $pid = isset($user['pid'])?$user['pid']:$user['id'];
        $company = Db::table('xfy_company')->where(['user_id'=>$pid])->first();
        return $company;
    }

    public function getProjectlist(Request $request){
        $info = $request->all();
        $adminuser = Db::table('admin_role_users')->where(['user_id'=>$info['adminId']])->first();
        if($adminuser['role_id']==2){ //代理人
            $list = Db::table('xfy_project')->where(['user_id'=>$info['adminId']])->get()->toArray();
        }
        if($adminuser['role_id']==3||$adminuser['role_id']==5){ //用户
//          $user = Db::table('admin_users')->where(['id'=>$info['adminId']])->first();
            $list = Db::table('xfy_project')->where(['user_id'=>$adminuser['pid']])->get()->toArray();
        }
        if($adminuser['role']==4){ //维修人员
            $list = Db::table('xfy_project')->get()->toArray();
        }
        print_r($list);die;
        // $user = Db::table('admin_users')->where(['admin_users.openid'=>$info['openid']])->leftJoin('admin_role_users', 'admin_users.id', '=', 'admin_role_users.user_id')->first();
        // if($user['id']==1||$user['role_id']==4){
        //  $project = Db::table('xfy_project')->get(['projectId','projectname','remark'])->toArray();
        // }else{
        //  $pid = isset($user['pid'])?$user['pid']:$user['id'];
        //  $project = Db::table('xfy_project')->where(['user_id'=>$pid])->get(['projectId','projectname','remark'])->toArray();
        // }
        return $list;
    }

    public function getproject(Request $request){
        $info = $request->all();
        $companylist = $this->getProjectlist($info['openid']);
        // Db::table('admin_users')-
    }

    public function getDevicelist(Request $request){
        $info = $request->all();
        $where = [
                    ['projectId', '=', $info['projectId']],
                    ['status', '>', 0],
                ];
        // $where1 = [
           //   ['projectId','=',$info['projectId']],
           //   ['pid','>',0]
        //  ];
        $p = Db::table('xfy_device')->where(['projectId'=>$info['projectId'],'pid'=>0])->orderByDesc('status')->get()->toArray();
        // $s = Db::table('xfy_device')->where($where1)->get()->toArray();
        // foreach ($p as $pk => &$pv){
        //  if($pv['device_type']==3){
        //      foreach ($s as $sk => $sv){
        //          if($pv['deviceId']==$sv['pid']){
        //              $pv[$sv['cid']] = $sv['status'];
        //          }
        //      }
        //  }
        // }
        // $t = array_column($p,null,'projectId');
        // $devicelist = Db::table('xfy_device')->join('xfy_room', 'xfy_device.roomId', '=', 'xfy_room.roomId')->where(['xfy_device.projectId'=>$info['projectId']])->orderByDesc('xfy_device.deviceId')->get(['xfy_device.deviceId as id','xfy_device.cid','xfy_device.devicename','xfy_device.roomId','xfy_device.devicename','xfy_device.address','xfy_device.lat','xfy_device.lng','xfy_device.status','xfy_device.updated_at','xfy_device.status','xfy_room.roomname','xfy_device.device_type','xfy_device.current_ai1','xfy_device.current_ai2','xfy_device.voltage_ai3','xfy_device.voltage_ai4','xfy_device.batvoltage_ai5'])->groupBy('roomId')->toArray();
        $arr['汇总'] = Db::table('xfy_device')->where($where)->orderByDesc('xfy_device.deviceId')->get(['deviceId','cid','devicename','created_at','status','address','device_type','current_ai1','current_ai2','voltage_ai3','voltage_ai4','batvoltage_ai5','signal','heartbeat','updated_at','powerStatus','simualmStatus','unnormalStatus','sensiFault','almStatus','linkalmStatus','removeStatus'])->toArray();
        // $device = array_column($devicelist,null,'roomname');
//      print_r($arr);die;
        $room = Db::table('xfy_room')->where(['projectId'=>$info['projectId']])->get()->toArray();
        foreach ($room as $key2=>$value2){
            foreach ($p as $key=>$value){
                if($value['roomId']==$value2['roomId']){
                    $arr[$value2['roomname']][] = $value;
                }
            }
        }
        // $arr['room'] = $arr;
        // print_r($devicelist);die;
        // foreach ($devicelist as $key=>&$value){
        //  foreach ($room as $key2=>$value2){
        //      if($key==$value2['roomId']){
        //          $arr[$value2['roomname']] = $value;
        //      }
        //  }
        // }
        // $arr = array_unshift($arr,$summary);
//      print_r($arr);die;
        // print_r($devicelist);die;
        return $arr;
    }
    //数组分组
    protected function dataGroup(array $dataArr,string $keyStr)   :array
    {
        $newArr=[];
        foreach ($dataArr as $k => $val) {    //数据根据日期分组
            $newArr[$val[$keyStr]][] = $val;
        }
        return $newArr;
    }

    public function getMapDevice(Request $request){
        $info = $request->all();
        $devicelist = Db::table('xfy_device')->where(['projectId'=>$info['projectId']])->get(['deviceId as id','cid','devicename','roomId','devicename','address','lat','lng','avatar','status','updated_at','status'])->toArray();
        return $devicelist;

    }

    // public function getLog(Request $request){
    //  // 获取到当前currentpage 和perpage 每页多少条
 //           $currentPage = (int)$request->input('current_page');
 //           $perage = (int)$request->input('perpage');
 //           $limitprame = ($currentPage -1) * $perage;
 //           $info = DB::table('xfy_device_log')->skip($limitprame)->take($perage)->where(['deviceId'=>$request->input('deviceId')])->orderByRaw('created_at')->get();
 //           $data = [
 //               'status'=> 1,
 //               'data' => [
 //                   'data' => $info,
 //                   'currentPage' => $currentPage
 //               ]
 //           ];
 //           return  $data;
    // }

    public function getDevice(Request $request){
        $info = $request->all();
        $device = Db::table('xfy_device')->where(['deviceId'=>$info['deviceId']])->first();
        if($device['roomId']==0){
            $info = Db::table('xfy_project')->where(['projectId'=>$device['projectId']])->first();
        }else{
            $info = Db::table('xfy_room')->where(['roomId'=>$device['roomId']])->first();
        }
        $device['device_arr'][0] = $device;
        if($device['device_type']==3){
            $device['di'] = Db::table('xfy_device')->where([['pid', '=', $device['deviceId']],['cid', 'like', '%DI%']])->get(['deviceId','cid','alarm','width','height','pageX','pageY','color'])->toArray();
            $device['ai'] = Db::table('xfy_device')->where([['pid', '=', $device['deviceId']],['cid', 'like', '%AI%']])->get(['deviceId','cid','alarm','width','height','pageX','pageY','color'])->toArray();
            $device['device_arr'] = array_merge($device['di'],$device['ai'],$device['device_arr']);
        }
        $device['planeJPG'] = $info['planeJPG'];
        return $device;
    }

    public function getDeviceMap(Request $request){
        $info = $request->all();
        $device = Db::table('xfy_device')->where(['deviceId'=>$info['deviceId']])->first();
        if($device['roomId']==0){
            $info = Db::table('xfy_project')->where(['projectId'=>$device['projectId']])->first();
        }else{
            $info = Db::table('xfy_room')->where(['roomId'=>$device['roomId']])->first();
        }
        $device['device_arr'][0] = $device;
        if($device['device_type']==3){
            $device['di'] = Db::table('xfy_device')->where([['pid', '=', $device['deviceId']],['cid', 'like', '%DI%']])->get(['deviceId','cid','devicename','status','width','height','pageX','pageY','color'])->toArray();
            $device['ai'] = Db::table('xfy_device')->where([['pid', '=', $device['deviceId']],['cid', 'like', '%AI%']])->get(['deviceId','cid','devicename','status','width','height','pageX','pageY','color'])->toArray();
            $device['device_arr'] = array_merge($device['di'],$device['ai'],$device['device_arr']);
        }
        $device['planeJPG'] = $info['planeJPG'];
        return $device;
    }

    public function searchDevice(Request $request){
        $info = $request->all();
        $where = [
                    ['projectId', '=', $info['projectId']],
                    ['cid', 'like', '%'.$info['key'].'%'],
            ];
        $result = Db::table('xfy_device')->where($where)->get()->toArray();
        // print_r($result);die;
        return $result;
    }

    public function summary(Request $request){
        $info = $request->all();
        $where['projectId'] = $info['key'];
        $where = [
                    ['projectId', '=', $info['key']],
                    ['status', '>', 0],
                ];
        $result = Db::table('xfy_device')->where($where)->get()->toArray();
        return $result;
    }

    public function getroom(Request $request){
        $info = $request->all();
        $res = Db::table('xfy_room')->where(['projectId'=>$info['key']])->get(['roomId','roomname'])->toArray();
        $arr = array('roomId'=>0,'roomname'=>'请选择');
        array_unshift($res,$arr);
        // $res = array_column($res, 'roomname', 'roomId');

        // print_r($res);die;
        // $res = array_combine(array_column($res, 'roomId'), $res);
        // foreach ($res as $key => &$value) {
        //     $res[$key] = $value['roomname'];
        // }
        // print_r(array_values($res));die;
        // print_r($res);die;
        return json_encode($res);
    }

    public function uploadFire(Request $request){
        $info = $request->all();
        if($info['status']==1){
            $msg = '真实报警';
        }else{
            $msg = $info['status']==2?'环境测试':'设备误报';
        }
        $update[$info['dstatus']] = 0;
        $update['status'] = 0;
    //  DB::connection()->enableQueryLog();#开启执行日志
        DB::table('xfy_device')->where(['deviceId'=>$info['deviceId']])->update($update);
        $log = DB::table('xfy_device_log')->where(['deviceId'=>$info['deviceId'],'device_detail'=>$info['dstatus']])->orderByDesc('created_at')->first();
    //  print_r(DB::getQueryLog());die;
    //  print_r($log);die;
        $time = date("Y-m-d H:i:s");
        // DB::connection()->enableQueryLog();#开启执行日志
        DB::table('xfy_device_log')->where(['deviceId'=>$info['deviceId'],'id'=>$log['id']])->update(['status'=>1,'result'=>$msg,'updated_at'=>$time,'remark'=>$info['remark'],'user_id'=>$info['adminid']]);
        // print_r(DB::getQueryLog());die;   //获取查询语句、参数和执行时间
        return json_encode(array('status'=>'1','msg'=>'处理成功'));
        // print_r($info);die;
    }

    /** 参数role【1为主管,2为用户】   **/
    public function addUser(Request $request){
        $info = $request->all();
        $user = Db::table('admin_users')->where(['username'=>$info['username']])->first();
        // print_r($user);die;
        $role = $info['role']==1?5:3; //5主管 3用户
        unset($info['_url']);
        unset($info['role']);
        $info['password'] = Hash::make($info['password']);
        if(!$user){
            $info['created_at'] = date("Y-m-d H:i:s");
            $res = Db::table('admin_users')->insertGetId($info);
            Db::table('admin_role_users')->insert(['role_id' => $role, 'user_id' => $res]);
            return 1;
        }else{
            DB::table('admin_users')->where(['id'=>$user['id']])->update(['name'=>$info['name'],'password'=>$info['password']]);
            return 2;
        }
    }

    /*根据项目id获取用户列表*/
    public function getUserlist(Request $request){
        $info = $request->all();
        $list = Db::table('admin_users')->where(['projectId'=>$info['projectId']])->get()->toArray();
        return $list;
    }

    public function addProject(Request $request){
        $info = $request->all();
        $res = Db::table('xfy_project')->where(['projectname'=>$info['projectname']])->first();
        if($res){
            return 2;
        }else{
            unset($info['_url']);
            $user = Db::table('admin_users')->where(['id'=>$info['user_id']])->first();
            $info['companyId'] = $user['companyId'];
            $info['created_at'] = date("Y-m-d H:i:s");
            Db::table('xfy_project')->insert($info);
            return 1;
        }
    }

    public function getUsers(Request $request){
        $info = $request->all();
        $list = Db::table('admin_users')->where(['projectId'=>$info['projectId']])->get()->toArray();
        $res = array_combine(array_column($list, 'id'), $list);
    //  print_r($res);die;
        foreach ($res as $key => &$value) {
            $res[$key] = $value['name'];
        }
        return $res;
        // print_r($list);die;
    }

    public function addTask(Request $request){
        $info = $request->all();

        $admin_info['admin_id'] = $info['adminId'];
        $admin_info['taskname'] = $info['taskname'];
        $admin_info['taskcontent'] = $info['taskcontent'];
        $admin_info['projectId'] = $info['projectId'];
        $admin_info['created_at'] = date("Y-m-d H:i:s");
        $id = Db::table('xfy_task')->insertGetId($admin_info);
        $user_info['taskId'] = $id;
        $user_info['created_at'] = date("Y-m-d H:i:s");
        $user_info['status'] = 0;
        foreach (json_decode($info['user'],1) as $key => &$value) {
            $user_info['user_id'] = $value;
            $this->sendWx($value,$id,$info['taskcontent'],$info['projectId']);
            Db::table('xfy_task_user')->insert($user_info);
        }
        return 1;
    }

    public function sendWx($user_id,$taskid,$taskcontent,$projectId){
        $user = Db::table('admin_users')->where(['id'=>$user_id])->first();
        $user = Db::table('users')->where(['unionid'=>$user['unionid']])->first();
        $project = Db::table('xfy_project')->where(['projectId'=>$projectId])->first();
        $app = app('wechat.official_account');
        if($user['openid']){
        $res = $app->template_message->send([
                'touser' => $user['openid'],
                'template_id' => 'wKqlkfSZPuy3G6iRzVAmlPtTVUvYDuN9WNuTNivMYpY',
                'miniprogram' => [
                        'appid' => 'wx301bce58badb7cc3',
                        'page' => 'pagepath/authorize?taskid='.$taskid.'&projectId='.$projectId,
                ],
                'data' => [
                    "first" => [
                        "value"=>"收到新任务",
                        "color"=>"#173177"
                    ],
                    "keyword1" => [
                        "value"=>date("Y-m-d H:i:s"),
                        "color"=>"#173177"
                    ],
                    "keyword2"=> [
                        "value"=>$project['projectname'],
                        "color"=>"#173177"
                    ],
                    "keyword3"=> [
                        "value"=>$taskcontent,
                        "color"=>"#173177"
                    ],
                    "remark" => [
                        "value"=>'请尽快处理',
                        "color"=>"#173177"
                        ]
                ],
            ]);
        }
    }

    public function taskList(Request $request){
        $info = $request->all();
        if($info['role']==3){ //普通用户
            $task_list = Db::table('xfy_task_user')->where(['xfy_task_user.user_id'=>$info['adminid']])->leftJoin('xfy_task', 'xfy_task.taskId', '=', 'xfy_task_user.taskId')->orderByDesc('xfy_task.taskId')->get()->toArray();
        }else{
            $task_list = Db::table('xfy_task')->where(['admin_id'=>$info['adminid']])->orderByDesc('taskId')->get()->toArray();
        }
        return $task_list;
    }

    public function getTask(Request $request){
        $info = $request->all();
        $task = Db::table('xfy_task')->where(['taskId'=>$info['taskId']])->first();
        return $task;
    }

    public function gitTask(Request $request){
        $info = $request->all();
        Db::table('xfy_task_user')->where(['taskId'=>$info['taskId'],'user_id'=>$info['adminId']])->update(['status'=>1,'remark'=>$info['remark'],'updated_at'=>date("Y-m-d H:i:s")]);
        return 1;
    }

    public function getDeviceLog(Request $request){
        // 获取到当前currentpage 和perpage 每页多少条
        $currentPage = (int)$request->input('p');
        $perage = 10;
        $limitprame = ($currentPage -1) * $perage;
        $data = DB::table('xfy_device_log')->skip($limitprame)->take($perage)->where(['xfy_device_log.deviceId'=>$request->input('deviceid')])->leftJoin('admin_users', 'admin_users.id', '=', 'xfy_device_log.user_id')->orderByDesc('xfy_device_log.created_at')->get(['xfy_device_log.*','admin_users.name'])->toArray();
        foreach ($data as $key => &$value){
            if($value['name']==''){
                $value['name'] = '无';
            }
        }
        echo  json_encode($data);
    }

    public function testlog(request $request){
        // $info = $request->all();
        $info = array (
          'encrypt' => 'xR19yGUPwDcJ1Nfp+AeoWJJS5HPfgi0IYGHM61L+Zvy1vfVms5Cgb8PPgGNhz7JkcoEZK9FpQpJF1Z/WRpOa7fugoLTo/CPCIDOYovNbgJh5G4glFqv93nDpzXVqAXGjM4Ddjw5/olRxSto+sSEOC/XIZMQD0S5mgrotb4D/JnqUTPTlUFENGEEFwsWoxJuGaiiAb+19ecOyoDEA++9COg==',
          '_url' => '/api/miniback',
          'signature' => 'd635b9de8e7a77a1107f881b141bf2612e18cfe4',
          'timestamp' => '1596179715805',
          'nonce' => 'VbPn6cmS',
        );
        // print_r($info);die;
        $res = base64_decode($info['encrypt']);
        // $a = openssl_decrypt($res, 'AES-128-CBC', '3g3i59q6td1u2r1ifol0rnzrcqrydk5ia0uu5q6ao4z', 0);
        $a = mcrypt_decrypt('MCRYPT_RIJNDAEL_128', '3g3i59q6td1u2r1ifol0rnzrcqrydk5ia0uu5q6ao4z',$res,'MCRYPT_MODE_CBC', '3g3i59q6td1u2r1ifol0rnzrcqrydk5ia0uu5q6ao4z');
        print_r($a);die;
        die;


        $rand_msg=AES_Decrypt($res);
        print_r($res);die;
        Log::info($info);
    }


    /** 微信锁 开门 **/
    public function open(Request $request){
        $info = $request->all();
        //测试ali_iot
        require '../vendor/iot_sdk/Test.php';
        $str = '{"reqId":"'.$info['cid'].'","command":"open","sendTime":'.time().',"ttl":10,"body":{}}';
        $strbase = base64_encode($str);
        $productKey = 'a1zQYVHQ92L';
        $deviceName = $info['cid'];
        $messageContent = $strbase;
        $t = new \Test();
        $result = $t->pubTest($productKey, $deviceName, $messageContent);
        echo json_encode($result);
    }

    public function miniback(Request $request){ //钉钉微应用测试
        $info = $request->all();
        Log::info($info);
    }
    //首页数据记录
    public function getLinedata(Request $request){
        $info = $request->all();
        if($info['role']==2){ //代理人
            $list = Db::table('xfy_project')->where(['user_id'=>$info['uid']])->get()->toArray();
        }
        if($info['role']==3||$info['role']==5){ //用户
            $user = Db::table('admin_users')->where(['id'=>$info['uid']])->first();
            $list = Db::table('xfy_project')->where(['user_id'=>$user['pid']])->get()->toArray();
        }
        if($info['role']==4||$info['role']==1){ //维修人员
            $list = Db::table('xfy_project')->get()->toArray();
        }
        if($list){
            $project = array_column($list,'projectId');
            $device_arr = Db::table('xfy_device')->whereIn('projectId',$project)->get()->toArray();
            $device_str = implode(',',array_column($device_arr,'deviceId'));
    //      print_r($device_str);die;
            $time = date("Y-m-d 00:00:00",strtotime("-21 day"));
    //      DB::connection()->enableQueryLog();#开启执行日志
            $log_arr = Db::select("select * from `xfy_device_log` where `deviceId` in (".$device_str.") and `created_at` >= '".$time."'");
            $result['lineData'] = array();
            $result['barData'] = array();
            for($i=21; $i>=0; $i--){
                $startime = date("Y-m-d 00:00:00",strtotime("-".$i." day"));
                $e = $i-1;
                $endtime = date("Y-m-d 00:00:00",strtotime("-".$e." day"));
                $sum = 0;
                $num = 0;
                foreach ($log_arr as $val){
                       if($startime<$val['created_at']&&$val['created_at']<$endtime){
                           if($val['status']==1){
                               $num++;
                           }
                           $sum++;
                       }
                }
                $result['lineData'][] = $num;
                $result['barData'][] = $sum;
            }
//      $log_arr = Db::table('xfy_device_log')->whereIn('deviceId',$device_str)->whereDate('created_at','>=',"'".$time."'")->get()->toArray();
        return $result;
        }
    }

    public function logList(Request $request){
        $info = $request->all();
       // $str = '0a865352036320827000005e8986111826700813059600010131015e002e10e0010105f20a03';
       // print_r(substr($str,52,4));
       // $update = hexdec(substr($str,52,4)); //电池电压
       // print_r($info);
        $res = Db::table('xfy_device_log')->where(['deviceId'=>$info['id']])->latest()->limit(12)->get()->toArray();
       // print_r($res);die;
        foreach ($res as &$val){
            $val['name'] = $info['name'];
        }
       // print_r($res);
        return $res;
    }
}